package com.mb.app.service.impl;

import com.mb.app.domain.TbOrder;
import com.mb.app.domain.TbOrderReturn1;
import com.mb.app.service.IOrderReturnJobService;
import com.mb.app.service.ITbOrderReturn1Service;
import com.mb.app.service.ITbOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 退款订单超出时限自动删除服务实现
 * @author wlz
 * @create 2019-05-10 6:15 PM
 **/
@Service("orderReturnJobService")
public class OrderReturnJobServiceImpl implements IOrderReturnJobService {


    @Autowired
    private ITbOrderReturn1Service orderReturn1Service;

    @Autowired
    private ITbOrderService orderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int runReport() {

        // 查询退款订单 退款状态 return_order_status 为 0
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("return_order_status",0);
        List<TbOrderReturn1> orderReturn1s = orderReturn1Service.selectByMap(map);
        if (orderReturn1s != null && orderReturn1s.size() != 0) {
               for (int i = 0; i < orderReturn1s.size(); i++) {
                   TbOrderReturn1 orderReturn1 = orderReturn1s.get(i);
                   if (orderReturn1.getReqReturnTime() != null) {
                       long syuTime = this.getsSyuTime(orderReturn1.getReqReturnTime());
                       if (syuTime < 0) {
                            // 将orderReturn 删除
                           orderReturn1Service.deleteById(orderReturn1.getReturnOrderId());
                           // 修改订单状态
                           TbOrder order = orderService.selectById(orderReturn1.getOrderId());
                           if (order != null) {
                               if (order.getOrderStatus() == 15) {
                                   order.setOrderStatus(1);
                               }else {
                                   order.setOrderStatus(3);
                               }
                           }
                           order.setOrderId(orderReturn1.getOrderId());
                           orderService.updateById(order);
                        }
                   }
               }
        }
        return 1;
    }

    public long getsSyuTime(Date reqReturnTime) {
        long cjTime = reqReturnTime.getTime();
        long xzTime = new Date().getTime();
        long hfTime = xzTime - cjTime;
        long qiTime = 1000 * 60 * 60 * 24 * 7;
        long syuTime = qiTime - hfTime;
        return syuTime;
    }
}
